What is the difference between jQuery's prop() and attr() methods?
What is the difference between jQuery's prop() and attr() methods?
23309-May-2023
Updated on 11-May-2023
Home / DeveloperSection / Forums / What is the difference between jQuery's prop() and attr() methods?
What is the difference between jQuery's prop() and attr() methods?
Aryan Kumar
11-May-2023In jQuery, both the `prop()` and `attr()` methods can be used to get and set the values of attributes of DOM elements, but they have some differences in how they work.
The `attr()` method gets or sets the value of an attribute on an element. It works with HTML attributes as well as custom attributes that are not part of the HTML standard. When used to get the value of an attribute, `attr()` returns the value of the attribute as it is specified in the HTML code. When used to set the value of an attribute, `attr()` sets the attribute to the specified value.
For example, consider the following HTML code:
To get the value of the `data-myAttr` attribute using `attr()`, you can use the following code:
To set the value of the `data-myAttr` attribute using `attr()`, you can use the following code:
The `prop()` method, on the other hand, gets or sets the value of a property on an element. It is used to get or set the current state of a DOM element, such as its checked state, disabled state, or selected state. When used to get the value of a property, `prop()` returns the current state of the property. When used to set the value of a property, `prop()` sets the property to the specified value.
For example, consider the following HTML code:
To get the checked state of the `myInput` checkbox using `prop()`, you can use the following code:
To set the checked state of the `myInput` checkbox using `prop()`, you can use the following code:
In summary, the main difference between `attr()` and `prop()` is that `attr()` is used for getting and setting the values of HTML attributes and custom attributes, while `prop()` is used for getting and setting the values of properties on DOM elements, such as checked, disabled, or selected. It's important to use the appropriate method depending on the type of attribute or property you are working with.